<template>
    <div class="base-page">
        <!-- 列表 -->
        <div class="right" style="margin: 0;" v-if="viewList === true">
            <div class="e-table">
                <div class="top">
                    <div class="left">
                        <div class="left-btn">
                            <el-button type="primary"
                                @click="goAdd"
                                class="btn-greenYellow"
                            >新增</el-button>
                            <!-- <el-button type="primary"
                                :disabled="selectedData.length < 1"
                                @click="goBatch"
                                class="btn-greenYellow"
                            >批量修改</el-button> -->
                            <el-button type="primary"
                            >导入</el-button>
                            <el-button type="primary"
                            >导出</el-button>
                        </div>
                    </div>
                    <div class="search_box">
                        <el-input class="ipt" type="text"
                            placeholder="输入搜索关键字"
                            v-model="searchKey"
                            @blur="onSearch"
                        ><img src="@/assets/search.png" slot="suffix" @click="onSearch" /></el-input>
                        <!-- <div class="adverse">
                            <el-button type="primary" size="small">高级搜索</el-button>
                        </div> -->
                    </div>
                </div>
            </div>
            <div class="e-table">
                <el-table
                    class="table"
                    :style="{width: rightTableWidth}"
                    :height="rightTableHeight"
                    :data="tableData"
                    border
                    :cell-class-name="cellClsNm"
                    @selection-change="handleSelectionChange"
                    :header-row-class-name="headerClass"
                    :row-class-name="rowClass"
                    highlight-current-row
                    ref="tableRef"
                    v-sortTable="{ 'tableData': tableData, '_this': this, 'ref': 'tableRef' }"
                >
                    <el-table-column type="selection" width="55" fixed> </el-table-column>
                    <el-table-column label="序号" type="index" width="55" fixed> </el-table-column>
                    <el-table-column prop="orgName" label="机构名称" min-width="200"
                        class-name="blue-column"
                    >
                        <template slot-scope="{ row }">
                            <span @click="onEdit(row)">{{ row.orgName || '无'}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="currencyName" label="币种名称"> </el-table-column>
                    <el-table-column prop="state" label="引用状态" width="200">
                        <template slot-scope="{ row }">
                            {{ ['未引用', '已引用'][row.state] }}
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <Pagination
                :total="paginationInfo.total"
                :pageSize.sync="paginationInfo.pageSize"
                :currentPage.sync="paginationInfo.currentPage"
                @currentChange="getBaseCy"
                @sizeChange="getBaseCy"
            />
        </div>
        <!-- 新增编辑界面 -->
        <div class="right" v-else>
            <div class="e-form">
                <BillTop @cancel="onCancel"></BillTop>
                <div class="tabs scroll_bar"
                    id="tabs"
                    :style="{width: rightTabsWidth, height: rightTabsHeight-this.topHeight, overflow: 'auto'}"
                >
                    <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                        <el-tab-pane label="本位币信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                        <el-tab-pane label="人民币汇率信息" name="detail" :disabled="clickTabFlag"></el-tab-pane>

                        <div id="baseInfoCon" class="con">
                            <div class="tabs-title" id="baseInfo">本位币信息</div>
                            <el-form ref="form" :model="formData" label-width="150px"
                                :rules="rules"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="机构名称：" prop="orgName">
                                            <el-input v-model="formData.orgName" readonly placeholder="请选择机构"
                                                v-if="formData.state === 0"
                                            >
                                                <i slot="suffix" class="el-icon-document-copy" @click="onSelectOrg"
                                                    v-if="viewList !== 'batch'"
                                                ></i>
                                            </el-input>
                                            <span v-else>{{ formData.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="本位币："
                                            prop="currency"
                                        >
                                            <el-select v-model="formData.currency" filterable clearable placeholder="请选择"
                                                v-if="formData.state === 0"
                                            >
                                                <el-option
                                                    v-for="item in currencyOptions"
                                                    :key="item.kvId"
                                                    :label="item.kvKey"
                                                    :value="item.kvValue">
                                                </el-option>
                                            </el-select>
                                            <span v-else>{{ formData.currencyName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                        <div id="detailCon" class="con" v-if="viewList !== 'batch'">
                            <div class="tabs-title" id="detail">人民币汇率信息</div>
                            <div class="e-table">
                                <div style="margin: 0 0 10px;">
                                    <el-button type="primary"
                                        @click="onAddSub"
                                        class="btn-greenYellow"
                                    >新增</el-button>
                                    <el-button type="primary"
                                        class="btn-delete"
                                        :disabled="selectedDataSub.length < 1"
                                        @click="onDelSub"
                                    >删除</el-button>
                                    <span class="redFont"> {{ errTxt }}</span>
                                </div>
                                <el-table
                                    :data="tableData2"
                                    border
                                    :cell-class-name="cellClsNm"
                                    @selection-change="handleSelectionChangeSub"
                                    ref="tableRef2"
                                    v-sortTable="{ 'tableData': tableData2, '_this': this, 'ref': 'tableRef2' }"
                                >
                                    <el-table-column type="selection" width="55"> </el-table-column>
                                    <el-table-column label="序号" type="index" width="55"> </el-table-column>
                                    <el-table-column prop="currency" label="当地币">
                                        <template slot-scope="{ row }">
                                            <el-select v-model="row.currency" filterable clearable placeholder="请选择"
                                                @change="onSelectCurrency"
                                            >
                                                <el-option
                                                    v-for="item in currencyOptions"
                                                    :key="item.kvId"
                                                    :label="item.kvKey"
                                                    :value="item.kvValue">
                                                </el-option>
                                            </el-select>
                                        </template>
                                    </el-table-column>
                                    <el-table-column prop="rate" label="兑换人民币汇率">
                                        <template slot-scope="{ row }">
                                            <div style="width: calc(100% - 20px)">
                                                <el-input placeholder="请输入汇率" v-enterFloat2 v-model="row.rate" ></el-input>
                                            </div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
                    </el-tabs>
                </div>
            </div>
            <div class="footer">
                <div class="right-btn">
                    <el-button type="primary"
                        @click="onSave"
                    >保存</el-button>
                    <el-button type="primary"
                        class="btn-delete"
                        @click="onDel"
                    >删除</el-button>
                    <el-button
                        @click="onCancel"
                    >取消</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
// eslint-disable-next-line no-unused-vars
import { getCurrencyApi, getBaseCyApi, getRmbRateApi, addBaseCyApi, batchUpdateBaseCyApi, updateBaseCyApi, getBaseCyInfoApi, deleteBaseCyApi, batchSaveRmbRateApi } from '@/api/base/system'
import Pagination from '@/components/pagination/pagination'
// eslint-disable-next-line no-unused-vars
import { debounce, showLoading, hideLoading, selectDataClient, openAppClient, getUuid } from '@/utils/common'
import { mapMutations } from 'vuex'
export default {
    components: {
        Pagination,
    },
    computed: {
        // 列表宽度
        rightTableWidth () {
            return (this.screenWidth - 20) + 'px'
        },
        rightTableHeight () {
            if (this.paginationInfo.total > 0) {
                return this.screenHeight - 170
            } else {
                return this.screenHeight - 118
            }
        },
        // tabs内表格宽度
        rightTabsWidth () {
            return (this.screenWidth - 22) + 'px'
        },
        rightTabsHeight () {
            return (this.screenHeight - 74) + 'px'
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 115 - this.lastConHeight
        },
    },
    data () {
        return {
            viewList: true, // 显示列表还是编辑界面: true 显示列表 false 显示编辑界面
            searchKey: '',
            treeData: [],
            selectedData: [],
            selectedDataSub: [],
            curSelectOrg: {
                orgId: '',
                orgName: ''
            },
            paginationInfo: {
                total: 0,
                pageSize: 20,
                currentPage: 1,
            },
            attachTableData: [],
            formData: {
                orgName: '',
                currency: ''
            },
            currencyOptions: [],
            tabsName: 'baseInfo',
            tableData: [],
            tableData2: [],
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            idsTop: [],
            errTxt: '',
            rules: {
                orgName: [
                    { required: true, message: '请选择机构', trigger: 'blur' },
                ],
                currency: [
                    { required: true, message: '请选择本位币', trigger: 'blur' },
                ]
            }
        }
    },
    created () {
        this.getCurrency()
        this.getBaseCy()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 获取屏幕宽高
        this.getScreenInfo()
        // 注册滚动事件
        this.registScroll()

        window.addEventListener('resize', debounce(this.getScreenInfo))
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        // 获取币种字典值
        async getCurrency () {
            const currencyOptions = await getCurrencyApi({
                dicName: '币种',
                isEnable: false
            })
            this.currencyOptions = currencyOptions.filter(item => item.kvStatus)
        },
        // 获取币种设置列表
        async getBaseCy () {
            showLoading()
            try {
                const resData = await getBaseCyApi({
                    keyWord: this.searchKey,
                    limit: this.paginationInfo.pageSize,
                    page: this.paginationInfo.currentPage
                })
                this.tableData = resData.list
                this.paginationInfo.total = resData.totalCount
                hideLoading()
            } catch (err) {
                hideLoading()
            }
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        onSearch (e) {
            let searchKey = e
            if (typeof e === 'object') {
                searchKey = this.searchKey
            }
            this.paginationInfo.pageSize = 20
            this.paginationInfo.currentPage = 1
            this.searchKey = searchKey
            this.getBaseCy()
        },
        goAdd () {
            this.viewList = false
            this.formData = {
                orgId: '',
                orgName: '',
                currency: '',
                currencyName: '',
                recordId: '',
                state: 0
            }
            this.tableData2 = []
        },
        async onEdit ({ recordId }) {
            showLoading()
            try {
                // 获取选中币种信息
                const resData = await getBaseCyInfoApi({
                    Id: recordId
                })
                this.formData = resData
                // 获取机构下某币种的人民币汇率
                const resData2 = await getRmbRateApi({
                    orgId: resData.orgId
                })
                this.tableData2 = resData2
                this.viewList = false
                hideLoading()
            } catch (error) {
                hideLoading()
            }
        },
        headerClass () {
            const hasNone = this.tableData.some(item => item.state === 1)
            if (hasNone) {
                return 'none'
            } else {
                return ''
            }
        },
        rowClass ({ row }) {
            if (row.state === 1) {
                return 'none'
            } else {
                return ''
            }
        },
        goBatch () {
            this.viewList = 'batch'
            console.log(this.selectedData)
            this.formData.orgName = this.selectedData.map(item => item.orgName).join(',')
        },
        onSave () {
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    const noEmpty = this.tableData2.every(item => item.rate)
                    if (!noEmpty) {
                        this.errTxt = '人民币汇率必填，请检查确认'
                    } else {
                        this.errTxt = ''
                        showLoading()
                        try {
                            const curCurrency = this.currencyOptions.find(item => item.kvValue === this.formData.currency)
                            if (!this.formData.recordId && this.viewList !== 'batch') {
                                await addBaseCyApi({
                                    currency: this.formData.currency,
                                    currencyName: curCurrency.kvKey,
                                    orgId: this.curSelectOrg.orgId,
                                    orgName: this.curSelectOrg.orgName
                                })
                            } else if (this.viewList === 'batch') {
                                // 批量更新
                                const list = this.selectedData.map(item => ({
                                    currency: this.formData.currency,
                                    currencyName: curCurrency.kvKey,
                                    orgId: item.orgId,
                                    orgName: item.orgName,
                                    recordId: item.recordId,
                                    state: this.formData.state
                                }))
                                await batchUpdateBaseCyApi(list)
                            } else if (this.formData.state === 0) {
                                // 未被引用，则可以编辑
                                await updateBaseCyApi({
                                    currency: this.formData.currency,
                                    currencyName: curCurrency.kvKey,
                                    orgId: this.formData.orgId,
                                    orgName: this.formData.orgName,
                                    recordId: this.formData.recordId,
                                    state: this.formData.state
                                })
                            }
                            if (this.viewList !== 'batch') {
                                this.tableData2.forEach(item => {
                                    item.orgId = this.formData.orgId
                                    item.orgName = this.formData.orgName
                                })
                                // 保存机构下某币种的人民币汇率
                                await batchSaveRmbRateApi(this.tableData2)
                            }
                            this.getBaseCy()
                        } catch (err) {
                            console.log(err)
                            hideLoading()
                        }
                        this.viewList = true
                    }
                } else {
                    return false
                }
            })
        },
        onDel () {
            this.clientPop('info', '确定要删除吗？数据删除后不可恢复，请谨慎操作！', async () => {
                // 获取币种设置列表
                showLoading()
                console.log(this.formData)
                try {
                    await deleteBaseCyApi({
                        orgId: this.formData.orgId
                    })
                    hideLoading()
                    this.clientPop('suc', '删除成功', () => {
                        this.viewList = true
                        this.getBaseCy()
                    })
                } catch (e) {
                    hideLoading()
                }
            })
        },
        onCancel () {
            this.viewList = true
        },
        // 新增机构下某币种的人民币汇率
        onAddSub () {
            this.tableData2.push({
                id: getUuid(),
                currency: '',
                rate: ''
            })
        },
        onDelSub () {
            console.log(this.selectedDataSub)
            this.tableData2 = this.tableData2.filter(item => {
                return !this.selectedDataSub.find(sub => sub.rateId === item.rateId)
            })
        },
        // 选中
        handleSelectionChange (val) {
            this.selectedData = val
        },
        // 选中汇率
        handleSelectionChangeSub (val) {
            console.log(val)
            this.selectedDataSub = val
        },
        onSelectOrg () {
            selectDataClient({
                SelectServiceToken: '/hr/org/getChildrenOrg', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                Title: '选择机构' // 标题
            }).then(val => {
                this.curSelectOrg = val[0]
                this.formData.orgName = val[0].orgName
            })
        },
        onChangeTab (e) {
            const cur = this.idsTop.find(item => item.name === e.name)
            $('#tabs').scrollTo(cur.top, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('detailCon')) {
                    const lastConHeight = document.getElementById('detailCon').offsetHeight
                    this.lastConHeight = lastConHeight - 18
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        getScreenInfo () {
            let screenWidth = document.documentElement.clientWidth || document.body.clientWidth
            let screenHeight = document.documentElement.clientHeight || document.body.clientHeight
            this.screenWidth = screenWidth
            this.screenHeight = screenHeight
        },
        // 注册右侧tabs区域内滚动时定位
        registScroll () {
            let si = setInterval(() => {
                if (document.getElementById('tabs')) {
                    // 保存所有tabName
                    const arr = ['baseInfo', 'detail']
                    const me = this
                    let $idsTop = []
                    if (!$idsTop[$idsTop.length - 1]) {
                        $idsTop = arr.map(item => {
                            const $item = document.getElementById(item)
                            let itemTop = 0
                            if ($item) {
                                itemTop = $item.offsetTop
                            }
                            return {
                                name: item,
                                top: itemTop
                            }
                        })
                    }
                    this.idsTop = $idsTop

                    $('#tabs').on('scroll', function () {
                        // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
                        if (me.clickTabFlag) {
                            return
                        }

                        const scrollTop = $(this).get(0).scrollTop
                        // 倒序查找
                        let curLocal = 0
                        for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                            let item = $idsTop[i].top
                            if (scrollTop + 3 >= item) {
                                curLocal = i
                                break
                            }
                        }
                        // 设置对应tabName
                        me.tabsName = arr[curLocal]
                    })

                    clearInterval(si)
                    si = null
                }
            }, 100)
        }
    }
}
</script>

<style lang="scss" scoped>
.base-page {
    .right{
        margin: 0;
        .tabs {
            ::v-deep .el-tabs__header {
                left: 12px;
            }
        }
    }
}
::v-deep.el-input__suffix{
    display: flex;
    align-items: center;
}
.e-table .el-table{
    ::v-deep.none{
        .el-checkbox{display: none;}
    }
}
</style>
